import { Component, EventEmitter, Input, Output, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { StorehouseService } from '../storehouse.service';

interface ManagerGroup {
  department: string;
  managers: string[];
}

@Component({
  selector: 'app-manager-select-dialog',
  template: `
    <div class="dialog-overlay" *ngIf="visible" (click)="onOverlayClick($event)">
      <div class="dialog-container">
        <div class="dialog-header">
          <h3>{{title}}</h3>
          <button class="close-button" (click)="onCancel()">×</button>
        </div>
        <div class="dialog-body">
          <div class="search-box">
            <input type="text" 
                   [(ngModel)]="searchText" 
                   (ngModelChange)="onSearch()"
                   placeholder="请搜索...">
          </div>
          <div class="manager-list">
            <div *ngIf="isLoading" class="loading-state">
              加载中...
            </div>
            <div *ngIf="!isLoading && error" class="error-state">
              {{error}}
              <button (click)="loadManagers()">重试</button>
            </div>
            <div *ngIf="!isLoading && !error" class="manager-items">
              <div *ngIf="filteredManagers.length === 0" class="no-data">
                未找到匹配的人员
              </div>
              <div *ngFor="let manager of filteredManagers" 
                   class="manager-item"
                   [class.selected]="isSelected(manager)"
                   (click)="onSelect(manager)">
                <span class="check-icon" *ngIf="isSelected(manager)">✓</span>
                {{ manager }}
              </div>
            </div>
          </div>
        </div>
        <div class="dialog-footer">
          <button class="btn-cancel" (click)="onCancel()">取消</button>
          <button class="btn-confirm" (click)="onConfirm()">确定</button>
        </div>
      </div>
    </div>
  `,
  styles: [`
    .dialog-overlay {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: rgba(0, 0, 0, 0.5);
      display: flex;
      justify-content: center;
      align-items: center;
      z-index: 1000;
    }

    .dialog-container {
      background: white;
      border-radius: 4px;
      width: 500px;
      max-width: 90vw;
      max-height: 80vh;
      display: flex;
      flex-direction: column;
    }

    .dialog-header {
      padding: 16px;
      border-bottom: 1px solid #eee;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .dialog-header h3 {
      margin: 0;
      font-size: 16px;
      color: #333;
    }

    .close-button {
      background: none;
      border: none;
      font-size: 20px;
      cursor: pointer;
      color: #666;
    }

    .dialog-body {
      padding: 16px;
      overflow-y: auto;
      flex: 1;
    }

    .search-box {
      margin-bottom: 16px;
    }

    .search-box input {
      width: 100%;
      padding: 8px 12px;
      border: 1px solid #ddd;
      border-radius: 4px;
      font-size: 14px;
    }

    .manager-list {
      max-height: 400px;
      overflow-y: auto;
    }

    .loading-state,
    .error-state,
    .no-data {
      padding: 20px;
      text-align: center;
      color: #666;
    }

    .error-state {
      color: #ff4d4f;
    }

    .error-state button {
      margin-top: 8px;
      padding: 4px 12px;
      background: #fff;
      border: 1px solid #ff4d4f;
      color: #ff4d4f;
      border-radius: 4px;
      cursor: pointer;
    }

    .error-state button:hover {
      background: #fff1f0;
    }

    .manager-items {
      background: #fff;
    }

    .manager-item {
      padding: 8px 12px;
      cursor: pointer;
      display: flex;
      align-items: center;
      color: #333;
      font-size: 14px;
    }

    .manager-item:hover {
      background-color: #f0f7ff;
    }

    .manager-item.selected {
      background-color: #e6f7ff;
      color: #1890ff;
    }

    .check-icon {
      margin-right: 8px;
      color: #1890ff;
    }

    .dialog-footer {
      padding: 16px;
      border-top: 1px solid #eee;
      display: flex;
      justify-content: flex-end;
      gap: 8px;
    }

    button {
      padding: 8px 16px;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px;
    }

    .btn-cancel {
      border: 1px solid #ddd;
      background: white;
      color: #666;
    }

    .btn-cancel:hover {
      color: #40a9ff;
      border-color: #40a9ff;
    }

    .btn-confirm {
      background: #1890ff;
      color: white;
      border: none;
    }

    .btn-confirm:hover {
      background: #40a9ff;
    }
  `],
  standalone: true,
  imports: [CommonModule, FormsModule]
})
export class ManagerSelectDialogComponent implements OnInit {
  @Input() visible = false;
  @Input() title = '选择人员';
  @Input() selectedManager = '';
  @Output() cancel = new EventEmitter<void>();
  @Output() confirm = new EventEmitter<string>();

  managers: string[] = [];
  filteredManagers: string[] = [];
  searchText = '';
  selectedValue = '';
  isLoading = false;
  error: string | null = null;

  constructor(private storehouseService: StorehouseService) {}

  ngOnInit() {
    this.selectedValue = this.selectedManager;
    this.loadManagers();
  }

  loadManagers() {
    this.isLoading = true;
    this.error = null;
    this.storehouseService.getWarehouseManagers().subscribe({
      next: (managers) => {
        console.log('Loaded managers:', managers);
        this.managers = managers || [];
        this.filteredManagers = [...this.managers];
        this.onSearch();
        this.isLoading = false;
      },
      error: (error) => {
        console.error('Failed to load managers:', error);
        this.error = '加载人员列表失败，请重试';
        this.isLoading = false;
      }
    });
  }

  onSearch() {
    if (!this.searchText) {
      this.filteredManagers = [...this.managers];
    } else {
      const searchLower = this.searchText.toLowerCase();
      this.filteredManagers = this.managers.filter(manager => 
        manager.toLowerCase().includes(searchLower)
      );
    }
  }

  isSelected(manager: string): boolean {
    return this.selectedValue === manager;
  }

  onSelect(manager: string) {
    this.selectedValue = manager;
  }

  onCancel() {
    this.cancel.emit();
  }

  onConfirm() {
    this.confirm.emit(this.selectedValue);
  }

  onOverlayClick(event: MouseEvent) {
    if ((event.target as HTMLElement).classList.contains('dialog-overlay')) {
      this.onCancel();
    }
  }
} 